<template>
  <view class="page-container">
    <!-- 日期选择器 -->
    <view class="date-selector">
      <scroll-view scroll-x class="date-scroll">
        <view class="date-list">
          <view 
            v-for="(date, index) in dateList" 
            :key="index"
            class="date-item"
            :class="{ active: selectedDate === date.value }"
            @click="selectDate(date.value)"
          >
            <text class="date-day">{{ date.day }}</text>
            <text class="date-date">{{ date.date }}</text>
            <text class="date-week">{{ date.week }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-left">
        <uni-data-select 
          v-model="queryParams.venue_id" 
          :localdata="venueOptions" 
          placeholder="选择场地"
          @change="handleVenueChange"
        ></uni-data-select>
      </view>
      <view class="filter-right">
        <view class="status-filters">
          <view 
            class="status-filter" 
            :class="{ active: queryParams.status === undefined }"
            @click="handleStatusFilter(undefined)"
          >
            全部
          </view>
          <view 
            class="status-filter" 
            :class="{ active: queryParams.status === 1 }"
            @click="handleStatusFilter(1)"
          >
            待确认
          </view>
          <view 
            class="status-filter" 
            :class="{ active: queryParams.status === 2 }"
            @click="handleStatusFilter(2)"
          >
            已确认
          </view>
          <view 
            class="status-filter" 
            :class="{ active: queryParams.status === 3 }"
            @click="handleStatusFilter(3)"
          >
            进行中
          </view>
        </view>
      </view>
    </view>

    <!-- 预订时间表 -->
    <scroll-view
      scroll-y
      class="booking-scroll"
      refresher-enabled
      @refresherrefresh="handleRefresh"
      :refresher-triggered="isRefreshing"
    >
      <view v-if="bookingList.length > 0" class="booking-timeline">
        <view 
          v-for="booking in bookingList" 
          :key="booking.id"
          class="booking-item"
          @click="navigateToDetail(booking.id)"
        >
          <view class="booking-time">
            <text class="time-start">{{ formatTime(booking.start_time) }}</text>
            <view class="time-line"></view>
            <text class="time-end">{{ formatTime(booking.end_time) }}</text>
          </view>
          
          <view class="booking-content">
            <view class="booking-header">
              <text class="booking-title">{{ booking.venue_name }}</text>
              <uni-tag 
                :text="getStatusText(booking.status)" 
                :type="getStatusType(booking.status)" 
                size="small"
              />
            </view>
            
            <view class="booking-info">
              <view class="info-row">
                <uni-icons type="person" size="14" color="#999"></uni-icons>
                <text class="info-text">{{ booking.customer_name }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="phone" size="14" color="#999"></uni-icons>
                <text class="info-text">{{ booking.customer_phone }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="wallet" size="14" color="#999"></uni-icons>
                <text class="info-text">¥{{ booking.total_amount }}</text>
              </view>
            </view>
            
            <view class="booking-actions" @click.stop>
              <button 
                v-if="booking.status === 1" 
                class="action-btn confirm" 
                @click="confirmBooking(booking)"
              >
                确认
              </button>
              <button 
                v-if="booking.status === 1" 
                class="action-btn cancel" 
                @click="cancelBooking(booking)"
              >
                取消
              </button>
              <button 
                v-if="booking.status === 2" 
                class="action-btn start" 
                @click="startBooking(booking)"
              >
                开始使用
              </button>
              <button 
                v-if="booking.status === 3" 
                class="action-btn finish" 
                @click="finishBooking(booking)"
              >
                结束使用
              </button>
              <button class="action-btn detail" @click="navigateToDetail(booking.id)">
                详情
              </button>
            </view>
          </view>
        </view>
      </view>
      
      <view v-if="bookingList.length === 0 && !loading" class="empty-container">
        <uni-icons type="calendar" size="60" color="#999"></uni-icons>
        <text class="empty-text">当日暂无预订</text>
      </view>
    </scroll-view>

    <!-- 新增预订按钮 -->
    <view class="fab" @click="navigateToCreate">
      <uni-icons type="plusempty" size="24" color="#fff"></uni-icons>
    </view>

    <!-- 统计信息弹窗 -->
    <uni-popup ref="statsPopup" type="bottom">
      <view class="stats-modal">
        <view class="modal-header">
          <text class="modal-title">今日统计</text>
          <uni-icons type="close" size="20" @click="closeStatsModal"></uni-icons>
        </view>
        <view class="stats-content">
          <view class="stats-grid">
            <view class="stat-item">
              <text class="stat-number">{{ todayStats.totalBookings || 0 }}</text>
              <text class="stat-label">总预订</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">{{ todayStats.confirmedBookings || 0 }}</text>
              <text class="stat-label">已确认</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">{{ todayStats.activeBookings || 0 }}</text>
              <text class="stat-label">进行中</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">¥{{ todayStats.totalRevenue || 0 }}</text>
              <text class="stat-label">营收</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchBookings, fetchVenuesByStore, updateBookingStatus } from '@/api/booking';
import type { Booking, BookingQuery, Venue } from '@/types/booking';

const bookingList = ref<Booking[]>([]);
const venueOptions = ref<{ value: number; text: string }[]>([]);
const dateList = ref<any[]>([]);
const selectedDate = ref('');
const loading = ref(false);
const isRefreshing = ref(false);
const statsPopup = ref<any>(null);
const todayStats = ref<any>({});

const queryParams = reactive<BookingQuery>({
  date: '',
  venue_id: undefined,
  status: undefined,
  store_id: undefined,
});

const storeId = ref<number | null>(null);
const venueId = ref<number | null>(null);

// 生成日期列表（未来7天）
const generateDateList = () => {
  const dates = [];
  const today = new Date();
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);
    
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const week = weekDays[date.getDay()];
    
    dates.push({
      value: date.toISOString().split('T')[0],
      day: i === 0 ? '今天' : i === 1 ? '明天' : `${month}月`,
      date: day.toString(),
      week: `周${week}`,
    });
  }
  
  dateList.value = dates;
  selectedDate.value = dates[0].value;
  queryParams.date = dates[0].value;
};

// 获取预订列表
const getBookingList = async () => {
  if (loading.value) return;
  loading.value = true;

  try {
    const res = await fetchBookings(queryParams);
    bookingList.value = res.list || [];
  } catch (error) {
    console.error('获取预订列表失败:', error);
    uni.showToast({ title: '获取预订列表失败', icon: 'none' });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
  }
};

// 获取场地列表
const getVenueList = async () => {
  if (!storeId.value) return;
  
  try {
    const res = await fetchVenuesByStore(storeId.value);
    venueOptions.value = [
      { value: 0, text: '全部场地' },
      ...res.list.map((venue: Venue) => ({ 
        value: venue.id, 
        text: venue.name 
      }))
    ];
  } catch (error) {
    console.error('获取场地列表失败:', error);
  }
};

const selectDate = (date: string) => {
  selectedDate.value = date;
  queryParams.date = date;
  getBookingList();
};

const handleVenueChange = () => {
  if (queryParams.venue_id === 0) {
    queryParams.venue_id = undefined;
  }
  getBookingList();
};

const handleStatusFilter = (status: number | undefined) => {
  queryParams.status = status;
  getBookingList();
};

const handleRefresh = () => {
  isRefreshing.value = true;
  getBookingList();
};

// 格式化时间
const formatTime = (timeStr: string) => {
  return timeStr.substring(0, 5);
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    1: '待确认',
    2: '已确认',
    3: '进行中',
    4: '已完成',
    5: '已取消',
  };
  return statusMap[status] || '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'default',
    5: 'error',
  };
  return typeMap[status] || 'default';
};

// 确认预订
const confirmBooking = async (booking: Booking) => {
  try {
    await updateBookingStatus(booking.id, 2);
    uni.showToast({ title: '预订已确认' });
    getBookingList();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 取消预订
const cancelBooking = (booking: Booking) => {
  uni.showModal({
    title: '确认取消',
    content: `确定要取消"${booking.customer_name}"的预订吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await updateBookingStatus(booking.id, 5);
          uni.showToast({ title: '预订已取消' });
          getBookingList();
        } catch (error) {
          uni.showToast({ title: '操作失败', icon: 'none' });
        }
      }
    }
  });
};

// 开始使用
const startBooking = async (booking: Booking) => {
  try {
    await updateBookingStatus(booking.id, 3);
    uni.showToast({ title: '已开始使用' });
    getBookingList();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 结束使用
const finishBooking = async (booking: Booking) => {
  try {
    await updateBookingStatus(booking.id, 4);
    uni.showToast({ title: '使用已结束' });
    getBookingList();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

const navigateToDetail = (id: number) => {
  uni.navigateTo({ url: `/pages/bookings/detail?id=${id}` });
};

const navigateToCreate = () => {
  const url = venueId.value 
    ? `/pages/bookings/create?venueId=${venueId.value}&storeId=${storeId.value}`
    : `/pages/bookings/create?storeId=${storeId.value}`;
  uni.navigateTo({ url });
};

const closeStatsModal = () => {
  statsPopup.value?.close();
};

onLoad((options: any) => {
  if (options.storeId) {
    storeId.value = Number(options.storeId);
    queryParams.store_id = storeId.value;
  }
  
  if (options.venueId) {
    venueId.value = Number(options.venueId);
    queryParams.venue_id = venueId.value;
  }
  
  generateDateList();
  getVenueList();
});

onShow(() => {
  getBookingList();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.date-selector {
  background-color: #fff;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.date-scroll {
  white-space: nowrap;
}

.date-list {
  display: flex;
  padding: 0 10px;
  gap: 15px;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  min-width: 60px;
  
  &.active {
    background-color: var(--primary-color);
    color: #fff;
  }
}

.date-day {
  font-size: 12px;
  margin-bottom: 2px;
}

.date-date {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 2px;
}

.date-week {
  font-size: 11px;
  opacity: 0.8;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-left {
  flex: 1;
  margin-right: 10px;
}

.status-filters {
  display: flex;
  gap: 8px;
}

.status-filter {
  padding: 4px 8px;
  border-radius: 12px;
  background-color: #f5f5f5;
  color: #666;
  font-size: 12px;
  
  &.active {
    background-color: var(--primary-color);
    color: #fff;
  }
}

.booking-scroll {
  flex: 1;
  height: 0;
}

.booking-timeline {
  padding: 10px;
}

.booking-item {
  display: flex;
  background-color: #fff;
  border-radius: var(--border-radius);
  margin-bottom: 10px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

.booking-time {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  background-color: #f8f9fa;
  padding: 15px 10px;
  position: relative;
}

.time-start, .time-end {
  font-size: 14px;
  font-weight: bold;
  color: var(--text-color);
}

.time-line {
  width: 2px;
  height: 20px;
  background-color: var(--primary-color);
  margin: 8px 0;
}

.booking-content {
  flex: 1;
  padding: 15px;
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.booking-title {
  font-size: 16px;
  font-weight: bold;
  color: var(--text-color);
}

.booking-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 13px;
  color: var(--text-color-secondary);
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-text {
  margin-left: 6px;
}

.booking-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  
  &.confirm {
    background-color: var(--primary-color);
    color: #fff;
  }
  
  &.cancel {
    background-color: #ff4757;
    color: #fff;
  }
  
  &.start {
    background-color: #2ed573;
    color: #fff;
  }
  
  &.finish {
    background-color: #ffa502;
    color: #fff;
  }
  
  &.detail {
    background-color: #f5f5f5;
    color: #666;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  padding-top: 100px;

  .empty-text {
    margin-top: 10px;
    font-size: 14px;
  }
}

.fab {
  position: fixed;
  right: 20px;
  bottom: 40px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: var(--primary-color);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
  z-index: 20;
}

.stats-modal {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: var(--primary-color);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-color-secondary);
}
</style>